<?php
/** 
*
* @package phpBB3 :: phpBB OpenID
* @version $Id: openid_login.php 77 2010-02-28 07:37:17Z jonzenor $
* @copyright (c) 2007 phpBB Group 
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
* @author: MasterZ - http://www.phpbb.com/community/memberlist.php?mode=viewprofile&u=83328
*
*/

// the OpenID Libraries included in this MOD require session_start()
// I hope to get rid of this soon
session_start();

// Notes from Obsidian have been added to the source.  Jon, please review them.
// They will either start with @todo or @note.

// Start phpBB Sessions and stuff
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require($phpbb_root_path . 'common.' . $phpEx);
require($phpbb_root_path . 'includes/functions_display.' . $phpEx);
require($phpbb_root_path . 'includes/functions_user.' . $phpEx);

// Include phpBB OpenID files
require($phpbb_root_path . 'includes/openid/common.' . $phpEx);
require($phpbb_root_path . 'includes/openid/openid_class.' . $phpEx);
require($phpbb_root_path . 'includes/openid/openid2username.' . $phpEx);
require($phpbb_root_path . 'includes/openid/openid_config.' . $phpEx);

// Start the phpBB OpenID mod class
$phpbb_openid = new phpbb_openID;

// Start session management
$user->session_begin();
$user->setup('ucp');

// Get some vars if they exist
$submit = isset($_GET['submit']) ? true : false;
$register = isset($_POST['register']) ? true : false;
$server_auth = isset($_GET['server_auth']) ? true : false;
$upgrade = isset($_GET['upgrade']) ? true : false;
$version = isset($_GET['version']) ? true : false;
$install = isset($_GET['install']) ? true : false;

// Set default values for some vars that will be used later
$showLogin = $showRegister = false;
$show_register = false;

define('OID_DEBUG', $oid_config['debug']);

// Install the phpBB OpenID MOD
if ($install)
{
	// Install the table only if it does not exist
	$sql = "CREATE TABLE IF NOT EXISTS " . OPENID_URLS_TABLE . " (
	id INT NOT NULL AUTO_INCREMENT ,
	user_id MEDIUMINT( 8 ) NOT NULL ,
	openid_url TEXT NOT NULL ,
	openid_clean_url TEXT NOT NULL ,
	PRIMARY KEY ( id )
	) TYPE = MYISAM ;";

	$result = $db->sql_query($sql);

	trigger_error('OPENID_INSTALL_COMPLETE');
}

// Upgrade the forum from previous, inferior OpenID MODs.
if ($upgrade)
{
	// Track number of users moved
	$updated = 0;

	// Start the sql multi-insert array
	$sql_array = array();

	// Move users openid urls to the new table
	$sql = "SELECT * FROM " . USERS_TABLE . "
		WHERE user_openid != ''";
			
	$result = $db->sql_query($sql);
	while ($row = $db->sql_fetchrow($result))
	{
		// Move users id to the new table
		$oid_uid = $row['user_id'];
		$oid_url = $row['user_openid'];
	
		$sql_array[] = array(
			'user_id' 			=> $oid_uid,
			'openid_url'		=> $db->sql_escape($oid_url),
			'openid_clean_url'	=> $db->sql_escape($phpbb_openid->cleanOidURL($oid_url))
		);

		/* 
		** Kept for acrhival purposes only
		** Will be cleaned up after the above is confirmed to work
		
		$sql = "INSERT INTO " . OPENID_URLS_TABLE . " SET
			user_id = '" . (int) $oid_uid . "',
			openid_url = '" . $db->sql_escape($oid_url) . "',
			openid_clean_url = '" . $db->sql_escape($phpbb_openid->cleanOidURL($oid_url)) . "'";
		
		$update_result = $db->sql_query($sql);
		*/
		
		$updated ++;
	}
		
	$db->sql_multi_insert(OPENID_URLS_TABLE, $sql_array);
	
	// Delete the column in the users table
	$sql = "ALTER TABLE " . USERS_TABLE . " DROP user_openid";
	$db->sql_query($sql);
	
	// Remove files that are no longer needed

	// List files
	$old_files = array("finish_auth.php", "new_openid_user.php", "try_auth.php");

	foreach ($old_files as $file)
	{
		unlink($phpbb_root_path . $file);
	}
	
	// Done
	trigger_error('UPGRADE_COMPLETE' . $updated);
}

// See if the forum was submitted, then get the openid_url and redirect to the OP
if ($submit)
{
	if (OID_DEBUG) { echo "Form Submitted<br /><br />"; }
	
	// Render a default page if we got a submission without an openid value
	$openid = request_var('openid_url', '');
	if (empty($openid))
	{
    	trigger_error('NO_OPENID_URL');
	}

	// Setup the URL
	$phpbb_openid->setup_url();

	// Begin the OpenID authentication process.
	$auth_request = $consumer->begin($openid);

	// Handle failure status return values.
	if (!$auth_request) 
	{
    	trigger_error('OPENID_ERROR_INVALID');
	}

	// Create a request for registration data
	$sreg = Auth_OpenID_SRegRequest::build(array('email', 'fullname'), array('nickname'));
	if (!$sreg) {
		trigger_error('OPENID_ERROR_SREG_FAIL');
	}
	$auth_request->addExtension($sreg);

	// Redirect the user to the OpenID server for authentication.  Store
	// the token for this authentication so we can verify the response.

	$phpbb_openid->processOID();
}

if ($server_auth)
{
//	if (OID_DEBUG) { echo "Server Response<br /><br />"; }
	// Get response from the OpenID provider
	$openid_return_to = request_var('openid_return_to', '');
	$response = $consumer->complete($openid_return_to);
	
	$status = $response->status;
	// Find authentication result
	if ($status == Auth_OpenID_CANCEL)
	{
		// Authentication was cancelled.
		trigger_error('OPENID_ERROR_CANCELLED');
	}
	else if ($status == Auth_OpenID_FAILURE)
	{
		trigger_error('OPENID_ERROR_AUTH_FAIL' . $response->message);
	}
	else if ($status == Auth_OpenID_SUCCESS)
	{
		$openid = $response->identity_url;
		
		// See if userid exists
		$user_id = $phpbb_openid->findOpenID($openid);
		
		// User exists, login
		if ($user_id)
		{
			if (OID_DEBUG) { echo "Login Success, userid = " . $user_id . "<br /><br />"; }
			
			$user->session_create($user_id, false, true);

			// Get Simple Registration info
			$sreg = new Auth_OpenID_SRegResponse();
			$sreg_obj = $sreg->fromSuccessResponse($response);
			$sreg_data = $sreg_obj->contents();
			
			if (@$sreg_data['email'])
			{
				// Update the users email address
				$phpbb_openid->updateEmail($user_id, $sreg_data['email']);
			}
			
			//$phpbb_openid->redirect('index.php');				
			$url = append_sid("{$phpbb_root_path}index.$phpEx", '');
			redirect($url, false, true);
			echo "<a href='" . $url . "'>Redirecting...</a><br /><br />" . $url;
		}
		else
		{
			$show_register = true;
		}
	}	
}

if ($show_register)
{
	// This is a new user, setup the registration form
	$phpbb_openid->setSessionVar('openid', $openid);
	
	// Setup user data if it is not setup already
	if (empty($user->lang))
	{
		$user->setup();
	}
	page_header($user->lang['OPENID_CREATE']);
	$template->assign_var("OPEN_ID", $openid);
	
	$suggest_username = "";
	
	// Get Simple Registration info
	$sreg = new Auth_OpenID_SRegResponse();
	$sreg_obj = $sreg->fromSuccessResponse($response);
	$sreg_data = $sreg_obj->contents();
	
	if (@$sreg_data['email'])
	{
		if (!validate_email($sreg_data['email']))
		{
			$template->assign_var("EMAIL_FROM_SREG", $sreg_data['email']);
		}
	}
	
	if (@$sreg_data['nickname'])
	{
		// See if the username exists
		if (!$phpbb_openid->usernameExists($sreg_data['nickname']))
		{
			// Username does not exist, suggest it
			$template->assign_var("NICKNAME_FROM_SREG", $sreg_data['nickname']);
			$suggest_username = $sreg_data['nickname'];
		}
	}
	
	if (@$sreg_data['fullname'])
	{
		$template->assign_var("FULLNAME_FROM_SREG", $sreg_data['fullname']);
	}
	
	// If sreg info was not set, try to get username from URL
	if (!$suggest_username)
	{
		// Try to get the username from the openid URL
		$autoUsername = $phpbb_openid->usernameFromOpenID($response->getDisplayIdentifier());
		// See if the username exists
		if (!$phpbb_openid->usernameExists($autoUsername))
		{
			$suggest_username = $autoUsername;
		}
	}

	// If Instant Registration set + username suggested + email set, then go ahead and register
	if ($oid_config['instant_registration'] && $sreg_data['email'] && $suggest_username)
	{
		if (!validate_email($sreg_data['email']))
		{
			$user_id = $phpbb_openid->createUser($suggest_username, $sreg_data['email'], $openid);
			$user->session_begin(true);
			$user->session_create($user_id, false, true);
//			$phpbb_openid->redirect('index.php');
			$url = append_sid("{$phpbb_root_path}index.$phpEx", '');
			redirect($url, false, true);
			echo "<a href='" . $url . "'>Redirecting...</a><br /><br />" . $url;
			exit;
		}
	}
	
	// Show registration form
	$template->assign_var("OPENID_GUESS", $suggest_username);
	$template->set_filenames(array("body" => "new_openid_user.html"));
	page_footer();
	exit;
}

// If registration form was submitted
if ($register)
{
	if (OID_DEBUG) { echo "Registration Form Submitted.<br /><br />"; }
	// See if openid is set in session
	if (!$phpbb_openid->getSessionVar('openid'))
	{
		trigger_error('OPENID_ERROR_DENIED');
	}
	
	// get form vars
	$username = request_var('username', '');
	$email = request_var('email', '');
	$choice = request_var('choice', '');
	$openid = $phpbb_openid->getSessionVar('openid');
	
	switch($choice)
	{
		case "create_new":
		if (!$phpbb_openid->usernameExists($username))
		{
			// See if email is invalid
			if (validate_email($email))
			{
				trigger_error('OPENID_ERROR_EMAIL');
			}
			
			// See if username is valid
			if ($phpbb_openid->usernameExists($username))
			{
				trigger_error('OPENID_ERROR_USERNAME');
			}

			$user_id = $phpbb_openid->createUser($username, $email, $openid);
			$user->session_create($user_id, false, true);
		}
		else
		{
			trigger_error('OPENID_ERROR_USERNAME');
		}
		break;
		
		case "bind_existed":
		default:
			$password = request_var('password', '', true);
			$result = $auth->login($username, $password, false, 1, false);
			if ($result['status'] == LOGIN_SUCCESS)
			{
				$user_id = $phpbb_openid->bind($result['user_row']['user_id'], $openid);
				$user->session_create($result["user_row"]["user_id"]);
			}
			else
			{
				trigger_error('OPENID_ERROR_AUTH_FAIL');
			}
		break;
	}
	//$phpbb_openid->redirect('index.php');
	$url = append_sid("{$phpbb_root_path}index.$phpEx", '');
	redirect($url, false, true);
	echo "<a href='" . $url . "'>Redirecting...</a><br /><br />" . $url;
}

?>